<?php
//更新基类
namespace App\Models\Scripts;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

abstract class Sysupdate
{
    private static $instance;
    protected $version_id;
    public $time = null;
    public $timestamp = null;

    public function __construct()
    {
        $this->time = Carbon::now();
        $this->timestamp = time();
    }

    public static function factory($version)
    {
        $modelPath = '\App\Models\Scripts\\'.$version;
        self::$instance = new $modelPath();
        return self::$instance;
    }


    public static function getSysVersionList()
    {
        $res = DB::table('sys_version')->orderBy('create_time','desc')->orderBy('id','desc')->get();
        if(!$res){
            return false;
        }
        $res = json_decode(json_encode($res),true);
        if(!is_array($res) || count($res)<1){
            return false;
        }
        return $res;
    }

    public function run_cmd($cmd, $input='')
    {
        $proc=proc_open($cmd, array(0=>array('pipe', 'r'), 1=>array('pipe', 'w'), 2=>array('pipe', 'w')), $pipes);
        fwrite($pipes[0], $input);fclose($pipes[0]);
        $stdout=stream_get_contents($pipes[1]);fclose($pipes[1]);
        $stderr=stream_get_contents($pipes[2]);fclose($pipes[2]);
        $rtn=proc_close($proc);
        return array(
            'stdout'=>$stdout,
            'stderr'=>$stderr,
            'return'=>$rtn
        );
    }

    public function clearCache()
    {
        $file_path = dirname(app_path());
        $cmd_str = "cd ".$file_path." && echo 'suc'";
        $cmd_str .= " && php artisan view:clear";
        $cmd_str .= " && php artisan cache:clear";
        $cmd_str .= " && php artisan config:clear";
        $res = $this->run_cmd($cmd_str);
        return $res;
    }

}
